package com.dcy.web.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaHttpMethod;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.dcy.system.model.Resource;
import com.dcy.system.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @Author：dcy
 * @Description:
 * @Date: 2019/11/8 8:47
 */
@Configuration
public class WebConfiguration implements WebMvcConfigurer {

    @Autowired
    private ResourceService resourcesService;

    @Value("${ignored}")
    private List<String> ignored;


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SaInterceptor(handler -> {
            // 拦截所有URL请求
            SaRouter.match("/**", r -> StpUtil.checkLogin());
            // 获取所有的路由表
            List<Resource> resourcesList = resourcesService.getRouterList();
            for (Resource resource : resourcesList) {
                // 匹配请求方式
                SaRouter.matchMethod(resource.getHttpMethod())
                        // 匹配请求地址
                        .match(resource.getResPath())
                        // 校验权限
                        .check(r -> StpUtil.checkPermission(resource.getPermission()));
            }
        })).addPathPatterns("/**").excludePathPatterns(ignored);
    }
}
